/**
 * 未配送
 */

import React from 'react';
import {
    Card, Table, Input, Form, Select, Row, Col, Checkbox, Modal, Tabs,
    DatePicker, Button, Switch, Icon, Divider, message, Popconfirm, Tooltip, Menu
} from 'antd';
import { Util, dayFormat } from 'tools/index';
import { $http } from 'containers/config/https';
import ReadCard from 'components/readcard/ReadCard';
import ColumnAuthoritysModel from 'pages/columnAuthority/ColumnAuthoritysModel';
import CommonPagination from 'components/pagination/index';
import RangeDatePicker from 'components/rangePicker/index';
import { PAGE_NUM_MORE_STATUS } from 'tools/statusConstants';
import { $loadTemplate } from '../../lodop/Common/Print.js';
import SendExpress from '../component/SendExpress';
import ShowPrescriptionModal from './ShowPrescriptionModal';
import ShowPrintListModal from './ShowPrintListModal';
import ShowUpdateAddressModal from './ShowUpdateAddressModal';
import '../courierStyle/index.less';
import moment from 'moment';
import store from 'store';

const { RangePicker } = DatePicker;
const Search = Input.Search;
const Option = Select.Option;
const { TabPane } = Tabs;
const noData = require('../image/noData.png')

class ShowHaveDistributionTabPane extends React.Component {

    constructor(props) {
        super(props);
        var date = new Date()
        var userData = JSON.parse(sessionStorage.getItem('userData'));
        this.state = {
            dataSource: [],
            total: 0,
            page: 1,
            pageSize: 10,
            size: 'small',
            userData: userData,
            activeKey: '1',
            presc: [],
            cmpresc: [],
            specNos: [],
            checkNos: [],
            curStatus: false
        }
    }

    componentWillReceiveProps(nextProp) {
        if (!Util.isEmpty(nextProp.distributionData) || !Util.isEmpty(nextProp.adressMsg)) {
            this.setState({
                distributionData: nextProp.distributionData,
                record: nextProp.record,
                adressMsg: nextProp.adressMsg,
                orderID: nextProp.orderID,
                patID: nextProp.patID,
            })
        } else {
            this.setState({
                distributionData: [],
                record: '',
                adressMsg: '',
                patID: '',
            })
        }
    }

    componentDidMount() {
        this.loadLocalMessage()
    }

    loadLocalMessage() {
        let data = {
            params: [{
                // compontName: "QueryCourierOrderPage",
                type: "C",
                reactCode: ['ShowHaveDistributionTabPane']
            }]
        }
        $http.post('urlDeault', this, {
            code: "01040073",
            data: data,
            success: (res) => {
                if (res.errorCode == '0') {
                    this.setState({
                        localeProvider: this.state.userData.language == 'EN' ? res.result.language.EN : res.result.language.CN
                    })
                }
            }
        })

    }

    //国际化
    setMessage(name, message) {
        return this.state.localeProvider && this.state.localeProvider[name] ? this.state.localeProvider[name][message] : ''
    }

    loadExpressMessage() {
        var { distributionData } = this.state;
        let distributionDataOption = []
        distributionData && distributionData.map((item, index) => {
            distributionDataOption.push(
                <Col span={5} style={{ margin: '3px 5px' }}><Card key={index} hoverable title={<div>
                    <div style={{ color: 'rgb(51, 51, 51)', fontWeight: 'bold' }}>
                        <span>{item.title}</span>&nbsp;&nbsp;
                        <span>{item.prescNo}</span>
                    </div>
                    <div><span>{this.setMessage('ShowHaveDistributionTabPaneDepart', 'descripts')}{item.relocDesc}</span>&nbsp;&nbsp;
                <span>{item.telphone}</span>
                    </div>
                </div>} extra={<span>{item.status}</span>}>
                    <div style={{ height: '120px', overflow: 'auto' }}>
                        {this.loadSunBody(item.data)}
                    </div>
                    <div style={{ textAlign: 'center', color: '#1890ff', cursor: 'pointer' }}
                        onClick={this.showPrescriptionModal.bind(this, item)}>{this.setMessage('ShowHaveDistributionTabPanePrescription', 'descripts')}</div>
                </Card></Col>
            )
        })
        return distributionDataOption
    }

    loadSunBody(data) {
        var sunBodyOption = []
        data && data.map((item, index) => {
            sunBodyOption.push(<div key={index} style={{
                height: 30, lineHeight: '30px',
                width: '100%', display: 'flex',
            }}>
                <div style={{ width: '60%' }} className='sunbody-esplise'><Tooltip title={item.ordDesc}>{item.ordDesc}
                </Tooltip></div>
                <span style={{ color: 'rgb(77, 193, 130)', width: '20%' }} className='sunbody-esplise'>
                    <Tooltip title={item.medOtherInfo}>{item.medOtherInfo}</Tooltip></span>
                <div style={{ width: '19.8%', textAlign: 'right' }}>{item.ordQty}</div>
            </div>)
        })
        return sunBodyOption
    }

    //寄快递
    handleSendExpress(status) {
        // this.expressRef.showModal()
        this.setState({
            isShowPrintListModal: true,
            receiveStatus: status
        })
    }

    onRef = (ref) => {
        this.expressRef = ref
    }

    handleTableInfo = () => {
        this.clearInput()
        var { handleTableInfo } = this.props;
        handleTableInfo && handleTableInfo()
    }

    clearInput() {
        this.setState({
            presc: [],
            cmpresc: [],
            specNos: [],
            checkNos: [],
            newCmpresc: [],
            newSpecNosc: [],
            newCheckNos: [],
            newPresc: [],
            distributionData: []
        })
    }

    showPrescriptionModal(data) {
        var params = {
            params: [{
                admID: data.admID,
                prescNo: data.prescNo,
                type: data.type,
            }]
        }
        $http.post('urlDeault', this, {
            code: "03030049",
            data: params,
            success: function (res) {
                if (res.errorCode == '0') {
                    this.setState({
                        prescriptData: res.result,
                        isShowPrescriptionModal: true
                    })
                }
            }
        });
    }

    hideModal(name) {
        this.setState({
            [name]: false
        })
    }

    onSubmit(data) {
        var params = {
            params: [{
                orderID: this.state.receiveStatus == 'again' ? undefined : this.state.orderID,
                patID: this.state.patID,
                expressID: data.expressID,
                expressPayID: data.expressPayID,
                sendStartDate: data.sendStartDate,
                sendStartTime: data.sendStartTime,
                parcelQuantity: data.parcelQuantity,
                expressType: data.expressType,
                tempRange: data.tempRange,
                hospID: this.state.userData.hospID,
                userID: this.state.userData.userID,
                oldOrderID: this.state.receiveStatus == 'again' ? String(this.state.orderID) : undefined
            }]
        }
        $http.post('urlDeault', this, {
            code: this.state.receiveStatus == 'again' ? '03030089' : "03030061",
            data: params,
            success: function (res) {
                if (res.errorCode == '0') {
                    message.success(this.setMessage('ShowHaveDistributionTabPaneOperation', 'descripts'))
                    var { handleTableInfo, loadData } = this.props;
                    handleTableInfo && handleTableInfo()
                    loadData && loadData(1)
                    this.hideModal('isShowPrintListModal')
                    if (data.recipeList == true) {
                        this.onSubmitRecipeList()//打印处方
                    }
                    if (data.printList == true) {
                        this.onSubmitPrint()//打印清单
                    }
                    if (data.label == true) {
                        this.onSubmitPrintLabel()//打印配送标签
                    }
                    if (data.distr == true) {
                        this.handlePrintDistribution()//打印诊断证明
                    }
                    if (data.EMR == true) {
                        this.handlePrintEMR()//打印病历
                    }
                }
            }
        });
    }

    onSubmitRecipeList() {
        var params = {
            params: [{
                orderID: this.state.orderID,
                userID: this.state.userData.userID,
                hospID: this.state.userData.hospID,
            }]
        }
        $http.post('urlDeault', this, {
            code: "03030066",
            data: params,
            success: function (res) {
                if (res.errorCode == '0') {
                    this.hideModal('isShowPrintListModal')
                    if (!Util.isEmpty(res.result)) {
                        var data = res.result
                        for (var i = 0; i < data.length; i++) {
                            $loadTemplate(data[i].template, data[i].printStr);
                        }
                    }
                }
            }
        });
    }

    onSubmitPrint() {
        var params = {
            params: [{
                orderID: this.state.orderID
            }]
        }
        $http.post('urlDeault', this, {
            code: "03030059",
            data: params,
            success: function (res) {
                if (res.errorCode == '0') {
                    this.hideModal('isShowPrintListModal')
                    // if (!Util.isEmpty(res.result.data)) {
                    //     $loadTemplate(res.result.template, res.result.data);
                    // }
                    if (!Util.isEmpty(res.result)) {
                        var data = res.result
                        for (var i = 0; i < data.length; i++) {
                            $loadTemplate(data[i].template, data[i].printStr);
                        }
                    }
                }
            }
        });
    }
    onSubmitPrintLabel() {
        var params = {
            params: [{
                orderID: this.state.orderID
            }]
        }
        $http.post('urlDeault', this, {
            code: "03030071",
            data: params,
            success: function (res) {
                if (res.errorCode == '0') {
                    this.hideModal('isShowPrintListModal')
                    // if (!Util.isEmpty(res.result.data)) {
                    //     $loadTemplate(res.result.template, res.result.data);
                    // }
                    if (!Util.isEmpty(res.result)) {
                        var data = res.result
                        for (var i = 0; i < data.length; i++) {
                            $loadTemplate(data[i].template, data[i].printStr);
                        }
                    }
                }
            }
        });
    }

    updateAddressModal() {
        this.setState({
            isShowUpdateAddressModal: true
        })
    }

    updateAddressMsg(data) {
        var params = {
            params: [{
                receiveCityID: data.receiveCityID,
                receiveAreaID: data.receiveAreaID,
                receiveVillageID: data.receiveVillageID,
                receiveProvinceID: data.receiveProvinceID,
                receiveAddress: data.receiveAddress,
                receiveMobile: data.receiveMobile,
                receiveName: data.receiveName,
                hospID: this.state.userData.hospID,
                userID: this.state.userData.userID,
                orderID: this.state.orderID
            }]
        }
        $http.post('urlS', this, {
            code: '03030062',
            data: params,
            success: function (res) {
                if (res.errorCode == '0') {
                    message.success(this.setMessage('ShowHaveDistributionTabPaneModified', 'descripts'))
                    this.hideModal('isShowUpdateAddressModal')
                    var { handleTableInfo } = this.props;
                    handleTableInfo && handleTableInfo()
                }
            }
        })
    }
    //打印发票 处方 清单
    handlePrint = (flag) => {
        var params = {
            params: [{
                hospID: sessionStorage.userData ? JSON.parse(sessionStorage.userData).hospID : "",
                userID: sessionStorage.userData ? JSON.parse(sessionStorage.userData).userID : "",
                orderID: this.state.orderID
            }]
        }
        $http.post('urlS', this, {
            code: flag == "1" ? '03030066' : (flag == '2' ? '03030059' : (flag == '3' ? '03030070' : '03030071')),
            data: params,
            success: function (res) {
                if (res.errorCode == '0') {
                    message.success(this.setMessage('ShowHaveDistributionTabPanePrinting', 'descripts'))
                    if (!Util.isEmpty(res.result)) {
                        var data = res.result
                        for (var i = 0; i < data.length; i++) {
                            $loadTemplate(data[i].template, data[i].printStr);
                        }
                    }
                }
            }
        })
    }

    //取消订单
    handleCannelOrder() {
        var params = {
            params: [{
                orderID: this.state.orderID
            }]
        }
        $http.post('urlS', this, {
            code: '03030037',
            data: params,
            success: function (res) {
                if (res.errorCode == '0') {
                    message.success('取消成功');
                    var { handleTableInfo, loadData } = this.props;
                    handleTableInfo && handleTableInfo()
                    loadData && loadData(1)
                }
            }
        })
    }

    //打印诊断证明
    handlePrintDistribution() {
        var params = {
            params: [{
                hospID: this.state.userData.hospID,
                locID: this.state.userData.locID,
                userID: this.state.userData.userID,
                // admID: this.state.patientData && this.state.patientData.admID,
                expressOrderID: this.state.orderID
            }]
        }
        $http.post('urlDeault', this, {
            code: "03050232",
            data: params,
            success: function (res) {
                if (res.errorCode == '0') {
                    var print = res.result;
                    if (!Util.isEmpty(print)) {
                        for (var i = 0; i < print.length; i++) {
                            $loadTemplate(print[i].template, print[i].printStr);
                        }
                    }
                    message.success('打印成功！')
                }
            }
        });
    }

    //打印病历
    handlePrintEMR() {
        var params = {
            params: [{
                hospID: this.state.userData.hospID,
                // locID: this.state.userData.locID,
                // userID: this.state.userData.userID,
                // admID: this.state.patientData && this.state.patientData.admID,
                expressOrderID: this.state.orderID
            }]
        }
        $http.post('urlDeault', this, {
            code: "10020005",
            data: params,
            success: function (res) {
                if (res.errorCode == '0') {
                    let templateCode = 'HLWMZBL';
                    $loadTemplate(templateCode, res.result);
                    // var print = res.result;
                    // if (!Util.isEmpty(print)) {
                    //     for (var i = 0; i < print.length; i++) {
                    //         $loadTemplate(print[i].template, print[i].printStr);
                    //     }
                    // }
                    message.success('打印成功！')
                }
            }
        });
    }

    render() {
        var { distributionData } = this.state;

        return <div style={{ height: '76vh' }} className='no-disbtn-body'>
            <SendExpress
                newPresc={this.state.newPresc}
                admID={this.state.admID}
                newCmpresc={this.state.newCmpresc}
                newSpecNosc={this.state.newSpecNosc}
                newCheckNos={this.state.newCheckNos}
                titleData={this.state.record}
                handleTableInfo={this.handleTableInfo}
                onRef={this.onRef}
            >
            </SendExpress>
            {/**处方详情 */}
            <ShowPrescriptionModal isShow={this.state.isShowPrescriptionModal}
                prescriptData={this.state.prescriptData}
                onHide={this.hideModal.bind(this, 'isShowPrescriptionModal')}>
            </ShowPrescriptionModal>
            {/**打印清单 */}
            <ShowPrintListModal isShow={this.state.isShowPrintListModal}
                adressMsg={this.state.adressMsg}
                onSubmit={this.onSubmit.bind(this)}
                onHide={this.hideModal.bind(this, 'isShowPrintListModal')}>
            </ShowPrintListModal>
            {/**修改收货地址 */}
            <ShowUpdateAddressModal isShow={this.state.isShowUpdateAddressModal}
                adressMsg={this.state.adressMsg}
                onSubmit={this.updateAddressMsg.bind(this)}
                onHide={this.hideModal.bind(this, 'isShowUpdateAddressModal')}>
            </ShowUpdateAddressModal>
            <div style={{ height: '80vh' }}>
                <div style={{ height: 48, lineHeight: '48px', borderBottom: '1px solid #e8e8e8' }} className="title">
                   <Row>
                   <Col span={4}>
                    < span>{this.setMessage('ShowHaveDistributionTabPaneTotal', 'descripts')}{this.state.distributionData && this.state.distributionData.length}</span>
                    </Col>
                    <Col span={20} style={{textAlign: "right"}}>
                    <Menu mode="horizontal">
                        <Menu.Item key="mail">
                            <Button type='primary' style={{ marginLeft: 5 }} onClick={this.handleSendExpress.bind(this)}
                                disabled={!Util.isEmpty(this.state.record) && this.state.record.statusCode == '01' ? false : true}>{this.setMessage('ShowHaveDistributionTabPaneDelivery', 'descripts')}</Button>
                        </Menu.Item>
                        <Menu.Item key="app" disabled>
                            <Button type="primary" style={{ marginLeft: 5 }} disabled={!this.state.orderID} onClick={() => this.handlePrint("1")}>{this.setMessage('ShowHaveDistributionTabPanePrescriptions', 'descripts')}</Button>
                        </Menu.Item>
                        <Menu.Item key="al">
                            <Button type="primary" style={{ marginLeft: 5 }} disabled={!this.state.orderID} onClick={() => this.handlePrint("2")}>{this.setMessage('ShowHaveDistributionTabPaneList', 'descripts')}</Button>
                        </Menu.Item>
                        <Menu.Item key="ali">
                            <Button type="primary" style={{ marginLeft: 5 }} onClick={() => this.handlePrint("3")}>{this.setMessage('ShowHaveDistributionTabPanechecklist', 'descripts')}</Button>

                        </Menu.Item>
                        <Menu.Item key="ipay">
                            <Button type="primary" style={{ marginLeft: 5 }} disabled={!this.state.orderID} onClick={this.handlePrintDistribution.bind(this)}>打印诊断证明</Button>

                        </Menu.Item>
                        <Menu.Item key="alipa">
                            <Button type="primary" style={{ marginLeft: 5 }} disabled={!this.state.orderID} onClick={this.handlePrintEMR.bind(this)}>打印病历</Button>

                        </Menu.Item>
                        <Menu.Item key="alip">
                            <Button type="primary" style={{ marginLeft: 5 }} disabled={!this.state.orderID} onClick={() => this.handlePrint("4")}>{this.setMessage('ShowHaveDistributionTabPanelabel', 'descripts')}</Button>

                        </Menu.Item>
                        <Menu.Item key="ipa">
                            <Button type="primary" style={{ marginLeft: 5 }} disabled={
                                (!Util.isEmpty(this.state.record) && (this.state.record.statusCode == '01' || this.state.record.statusCode == '06')) ? true : (!this.state.orderID ? true : false)}
                                onClick={this.handleCannelOrder.bind(this)}>取消订单</Button>
                        </Menu.Item>
                        <Menu.Item key="li">
                            <Button type="primary" style={{ marginLeft: 5 }} disabled={
                                (!Util.isEmpty(this.state.record) && (this.state.record.statusCode == '01')) ? true : (!this.state.orderID ? true : false)
                            }
                                onClick={this.handleSendExpress.bind(this, 'again')}>重新下单</Button>
                        </Menu.Item>
                    </Menu>
                    </Col>
                   </Row>
                </div>
             
                <div style={{ height: 40, lineHeight: '40px', borderBottom: '1px solid #e8e8e8' }}>
                    <div style={{ float: 'left' }}>
                        {this.setMessage('ShowHaveDistributionTabPaneReceiving', 'descripts')}<span>{!Util.isEmpty(this.state.adressMsg) ? this.state.adressMsg.receiveName : '--'}</span>&nbsp;&nbsp;
                        <span>{!Util.isEmpty(this.state.adressMsg) ? this.state.adressMsg.receiveMobile : '--'}</span>&nbsp;&nbsp;
                        <span>{!Util.isEmpty(this.state.adressMsg) ? this.state.adressMsg.receiveAddress : '--'}</span>&nbsp;&nbsp;
                        <span>{!Util.isEmpty(this.state.record) && this.state.record.expressNo ?
                            <span style={{ color: '#1999db' }}>( {this.setMessage('ShowHaveDistributionTabPaneLogistics', 'descripts')}{this.state.record.expressNo})</span> : ''}</span>
                    </div>
                    {!Util.isEmpty(this.state.record) && this.state.record.statusCode == '01' ?
                        <div style={{ float: 'right', marginRight: 10, cursor: 'pointer', color: '#1890ff' }}
                            onClick={this.updateAddressModal.bind(this)}> {this.setMessage('ShowHaveDistributionTabPaneModify', 'descripts')}</div> : null}
                </div>
                <Row style={{ marginTop: 5, height: '73vh', overflow: 'auto' }}>
                    {!Util.isEmpty(distributionData) ? this.loadExpressMessage() :
                        <div style={{ textAlign: 'center', marginTop: '10%' }}><img src={noData} /><div style={{ marginTop: 10 }}> {this.setMessage('ShowHaveDistributionTabPanerelevant', 'descripts')}</div></div>}
                </Row>
            </div>
        </div>
    }
}

export default Form.create()(ShowHaveDistributionTabPane);